package com.zjc;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Vector;

public class MessageListener {

    public MessageListener() {
        super();
    }

    public static volatile Vector<Connect> vector = new Vector<Connect>();

    public void listening(){
        System.out.println("消息队列工作中。。。。");
        while (true){
            if (vector.size() == 0){
                continue;
            }
            Connect pack = vector.remove(0);
            new Thread(()->{
                try{
                    System.out.println(pack.toString());
                    /* 转发请求流 */
                    this.forwardStream(pack);
                    /* 转发响应流 */
                    this.transferTo(pack.target, pack.source);
                }catch(Exception e){
                    e.printStackTrace();
                }finally {
                    Forward.close(pack);
                }
            }).start();
        }
    }

    public void transferTo(Socket source, Socket target){
        try{
            byte[] buffer = new byte[512];
            int read;
            InputStream is = source.getInputStream();
            OutputStream os = target.getOutputStream();
            while ((read = is.read(buffer)) >= 0) {
                os.write(buffer, 0, read);
                if (read < buffer.length){
                    break;
                }
            }
        }catch(Exception e){}

    }

    private void forwardStream(Connect connect){
        try{
            /* 读取头部 */
            HttpReader httpReader = new HttpReader(connect.source);
            if (connect.target == null){
                httpReader.setConnect(connect);
            }else {
                httpReader.setTargetHost(connect.target.getRemoteSocketAddress().toString().substring(1));
            }
            /* 解析body */
            httpReader.parseBody();
            /* 转发报文 */
            connect.target.getOutputStream().write(httpReader.getSource().getBytes());
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("write error");
        }
    }
}
